<?php

namespace addons\yiliao\controller\api;

use app\admin\model\yiliao\Banner as BannerModel;
use think\Db;
use fast\Http;
use app\admin\model\yiliao\Procate;
use app\admin\model\yiliao\Pro;
use app\admin\model\yiliao\Doctor;
use app\admin\model\yiliao\Shop;
use app\admin\model\yiliao\Promotion;
use app\admin\model\yiliao\Bookmark;
use app\admin\model\yiliao\Pointcate;
use app\admin\model\yiliao\Pointprd;
use app\admin\model\yiliao\Exorder;
use app\admin\model\yiliao\User;
use app\admin\model\yiliao\Log;
use app\admin\model\yiliao\User as UserModel;

class Product extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    
    public function logs()
    {
        $rows = Log::where(['yiliao_user_id'=>$this->user['userid']])->order("id desc")->field("id,point,name,createtime")->select();
        foreach($rows as $k=>$v){
            $rows[$k]['time']=date("Y-m-d H:i:s",$v['createtime']);
        }
        $this->success('', $rows);
    }
    public function records()
    {
        $rows = Exorder::where(['yiliao_user_id'=>$this->user['userid']])->order("id desc")->field("id,name,image,point,createtime")->select();
        foreach($rows as $k=>$v){
            $rows[$k]['image']=cdnurl($v['image'], true);
            $rows[$k]['time']=date("Y-m-d H:i:s", $v['createtime']);
        }
        $this->success('', $rows);
    }
    public function exchange()
    {
        $id = $this->request->param('id');
        $row = Pointprd::where(['id'=>$id])->find();
        Db::startTrans();
        try{
            if ($row['num']>0) {
                $user = User::where(['id'=>$this->user['userid']])->find();
                if ($user['jifen']>=$row['point']) {
                    $orderid = date("YmdHis").rand(100, 999);
                    $d=[];
                    $d['createtime'] = time();
                    $d['yiliao_user_id'] = $this->user['userid'];
                    $d['yiliao_pointprd_id']=$id;
                    $d['orderid'] = $orderid;
                    $d['name'] =$row['name'];
                    $d['image']=$row['image'];
                    $d['num']=1;
                    $d['point']=$row['point'];
                    $d['xingming'] =$this->request->param('name');
                    $d['mobile'] =$this->request->param('mobile');
                    $d['address'] =$this->request->param('address');
                    $d['beizhu'] =$this->request->param('beizhu');
                    $d['yiliao_company_id']=0;
                    $d['number']='';
                    $d['remark']='';
                    $d['admin_id']=0;
                    $d['status']=0;
                    $res = Exorder::insert($d);
                    if ($res) {
                       $log=[];
                       $log['createtime']=time();
                       $log['yiliao_user_id']=$this->user['userid'];
                       $log['name']='积分兑换'.$orderid;
                       $log['point']=-1*$row['point'];
                       $total = $user['jifen']-$row['point'];
                       $log['total'] = $total;
                       $log['type']=3;
                       Log::insert($log);
                       User::where(['id'=>$this->user['userid']])->update(['jifen'=>$total]);
                    } else {
                        $this->error('兑换失败');
                    }
                } else {
                    $this->error('积分不足');
                }
                
            } else {
                $this->error('商品已兑换完');
            }
            Db::commit();
            $this->success("兑换成功");
        } catch (\think\exception\ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
    }
    public function pointprddetail()
    {
        $id = $this->request->param('id');
        $row = Pointprd::where(['id'=>$id])->find();
        /*$images = explode(",", $row['images']);
        foreach ($images as $k=>$image){
            $images[$k] = cdnurl($image, true);
        }
        $row['images'] = $images;
        */
        $row['image']=cdnurl($row['image'], true);
        $row['content'] = preg_replace( '/(<img.*?)(style=.+?[\'|"])|((width)=[\'"]+[0-9]+[\'"]+)|((height)=[\'"]+[0-9]+[\'"]+)/i','$1', $row['content']);
        $row['content'] = str_replace("<img", "<img style='max-width:100%;height:auto;'", $row['content']);
        $this->success('', $row);
    }
    public function pointprd()
    {
        $keyword = $this->request->param('keyword');
        $cateid = $this->request->param('cateid');
        $where=[];
        $where['status'] = 1;
        if ($keyword) {
            $where['name'] = ['like',"%$keyword%"];
        }
        if ($cateid > 0) {
            $where['yiliao_pointcate_id'] = $cateid;
        }
        $rows = Pointprd::where($where)->order("id desc")->field("id,yiliao_pointcate_id,name,image,point")->select();
        foreach($rows as $k=>$v){
            $rows[$k]['image'] = cdnurl($v['image'], true);
        }
        $this->success('', $rows);
    }
    public function pointcate()
    {
        $rows = Pointcate::where(['status'=>1])->order("weigh desc")->select();
        $ret = [];
        $ret[]=['id'=>0,'tit'=>'全部'];
        foreach($rows as $v){
            $ret[]=['id'=>$v['id'],'tit'=>$v['name']];
        }
        $this->success('', $ret);
    }

    public function bookmarkdel()
    {
        $id = $this->request->param('id');
        $res = Bookmark::where(['yiliao_user_id'=>$this->user['userid'],'id'=>$id])->delete();
        if ($res) {
            $this->success('取消成功');
        } else {
            $this->error('取消失败');
        }
    }
    public function myBookmark()
    {
        $rows = Bookmark::alias("A")->join("yiliao_pro P", "A.yiliao_pro_id=P.id")->join("yiliao_procate C", "P.yiliao_procate_id=C.id")->where(['A.yiliao_user_id'=>$this->user['userid']])->order("A.id desc")->field("A.id,P.name,P.price,C.name as cate,P.image,A.yiliao_pro_id as pid")->select();
        foreach($rows as $k=>$v){
            $rows[$k]['image'] = cdnurl($v['image'], true);
        }
        $this->success('', $rows);
    }
    public function bookmark()
    {
        $id = $this->request->param('id');
        $row = Bookmark::where(['yiliao_pro_id'=>$id, 'yiliao_user_id'=>$this->user['userid']])->find();
        if ($row) {
            $res = Bookmark::where(['id'=>$row['id']])->delete();
            if ($res) {
                $this->success('取消成功', 0);
            } else {
                $this->error('取消失败');
            }
        } else {
            $d=[];
            $d['createtime'] = time();
            $d['yiliao_user_id'] = $this->user['userid'];
            $d['yiliao_pro_id']=$id;
            $res = Bookmark::insert($d);
            if ($res) {
                $this->success('收藏成功', 1);
            } else {
                $this->error('收藏失败');
            }
        }
        
    }
    
    /**
     * 首页分类九宫格
     */
    public function homeCate()
    {
        $rows = Procate::where(['status'=>'normal','homedata'=>1])->order('paixu desc,id desc')->field('id,name,image')->select();
        $ret=[];
//        $ret[]=['id'=>8,'name'=>'政策法规','image'=>'/static/images/mico1.png'];
        foreach ($rows as $v) {
            $ret[]=['id'=>$v['id'],'name'=>$v['name'],'image' => cdnurl($v['image'], true)];
        }
        $this->success('', $ret);
    }

    /**
     * 首页热门项目
     */
    public function homepro()
    {
        $isshop = $this->request->param('isshop', 0);
        $shopid = $this->request->param('shopid');
        $scene = $this->request->param('scene');
        $where=[];
        $where['status']='normal';
        $where['isdata']='yes';
        if ($isshop==1) {
			/*
			朋友圈单页模式:
			1.页面无登录态，与登录相关的接口，如 wx.login 均不可用
			2.不允许跳转到其它页面，包括任何跳小程序页面、跳其它小程序、跳微信原生页面
			3.若页面包含 tabBar，tabBar 不会渲染，包括自定义 tabBar
			4.本地存储与小程序普通模式不共用
			*/
			if($scene==1154){
				$shop = Shop::where(['status'=>'normal'])->order("weigh desc")->find();
				if($shop){
					$shopid = $shop['id'];
				}
			}
            $where[] = ['exp',Db::raw("FIND_IN_SET('$shopid',yiliao_shop_ids)")];
        }
        $rows = Pro::where($where)->field('id,price,name,image')->limit(4)->select();
        foreach ($rows as $k => $v) {
            $rows[$k]['image'] = cdnurl($v['image'], true);
        }
        $this->success('success', $rows);
    }

    /**
     * 全部分类
     */
    public function getCates()
    {
        $rows = Procate::where(['status'=>'normal'])->field('id,name,image')->select();
        $this->success('success', $rows);
    }

    public function prodetail()
    {
        $id = $this->request->param('id', 0);
        $hdid = $this->request->param('hdid', 0);
        $isminapp = $this->request->param('isminapp');
        $isshop = $this->request->param('isshop');
        $shopid = $this->request->param('shopid');
        $images1 = BannerModel::where(['status'=>'normal', 'cate'=>'index'])->order('paixu desc,id desc')->column('image');
//        $images1 = implode(',', $images1);
        foreach ($images1 as $k => $v) {
            $images1[$k] = cdnurl($v, true);
        }
        if ($hdid>0) {
            $huodong = Promotion::where(['id'=>$hdid])->find();
            $row = Pro::with(['cate'])->where('pro.id', $huodong['yiliao_pro_id'])->find();
            $images = explode(',', $huodong['images']);
            foreach ($images as $k => $v) {
                $images[$k]=cdnurl($v, true);
            }
            $row['images']=$images1;
            $row['image'] = cdnurl($row['image'], true);

            if ($isshop==1) {
                $shop = Shop::where(['id'=>$shopid])->find();
                $shop['image'] = cdnurl($shop['image'], true);
                $shopimages = explode(",", $shop['images']);
                foreach ($shopimages as $k => $v) {
                    $shopimages[$k] = cdnurl($v, true);
                }
                $shop['images'] = $shopimages;
                $row['shop']=$shop;
            } else {
                //容错 单门店后台只选一个
                $shops = Shop::where(['id'=>['in',$row['yiliao_shop_ids']],'status'=>'normal'])->order("weigh desc")->select();
                $shop = $shops[0];
                $shop['image'] = cdnurl($shop['image'], true);
                $shopimages = explode(",", $shop['images']);
                foreach ($shopimages as $k => $v) {
                    $shopimages[$k] = cdnurl($v, true);
                }
                $shop['images'] = $shopimages;
                $row['shop']=$shop;
            }

            
            $doctor=[];
            if ($row['yiliao_doctor_ids']) {
                $where = [];
                $where['id']=['in',$row['yiliao_doctor_ids']];
                if ($isshop==1) {
                    $where[] = ['exp',Db::raw("FIND_IN_SET('$shopid',yiliao_shop_ids)")];
                }
                $doctor = Doctor::where($where)->field('id,avatar,name,jibie,tags,area')->select();
                foreach ($doctor as $k => $v) {
                    $doctor[$k]['avatar'] = cdnurl($v['avatar'], true);
                }
            }
            $row['doctor']=$doctor;
            $row['name']=$huodong['name'];
            $row['hdprice']=$huodong['price'];
            $row['hd_end']=$huodong['end'];
            $row['hdid']=$huodong['id'];
            $row['content']=$huodong['content'];
        } else {
            $row = Pro::with(['cate'])->where('pro.id', $id)->find();
            $row['image']=cdnurl($row['image'], true);

            $images = explode(',', $row['images']);
            foreach ($images as $k => $v) {
                $images[$k] = cdnurl($v, true);
            }
            $row['images']=$images1;
            if ($isshop==1) {
                $shop = Shop::where(['id'=>$shopid])->find();
                $shop['image'] = cdnurl($shop['image'], true);
                $shopimages = explode(",", $shop['images']);
                foreach ($shopimages as $k => $v) {
                    $shopimages[$k] = cdnurl($v, true);
                }
                $shop['images'] = $shopimages;
                $row['shop']=$shop;
            } else {
                //容错 单门店后台只选一个
//                $shops = Shop::where(['id'=>['in',$row['yiliao_shop_ids']],'status'=>'normal'])->order("weigh desc")->select();
                $shops = Shop::where(['id'=>['in',2],'status'=>'normal'])->order("weigh desc")->select();
                $shop = $shops[0];
                $shop['image'] = cdnurl($shop['image'], true);
                $shopimages = explode(",", $shop['images']);
                foreach ($shopimages as $k => $v) {
                    $shopimages[$k] = cdnurl($v, true);
                }
                $shop['images'] = $shopimages;
                $row['shop']=$shop;
            }
           
            $doctor=[];
            if ($row['yiliao_doctor_ids']) {
                $where = [];
                $where['id']=['in',$row['yiliao_doctor_ids']];
                if ($isshop==1) {
                    $where[] = ['exp',Db::raw("FIND_IN_SET('$shopid',yiliao_shop_ids)")];
                }
                $doctor = Doctor::where($where)->field('id,avatar,name,jibie,tags,area')->select();
                foreach ($doctor as $k => $v) {
                    $doctor[$k]['avatar'] = cdnurl($v['avatar'], true);
                }
            }
            $row['doctor']=$doctor;
            $row['hdid']=0;
        }
        //海报
		if($this->user && $this->user['userid']>0){
			$data = UserModel::where(['id'=>$this->user['userid']])->find();
			$row['userid'] =$this->user['userid'];
			$row['nickname']=$data['nickname'];
		}else {
			$row['userid'] =0;
			$row['nickname']='';
		}
        if ($isminapp==1 && $this->user && $this->user['userid']>0) {
            //生成二维码
            ///www/wwwroot/xx/public
            $document_path = request()->server('DOCUMENT_ROOT');
            $path = '/uploads/yiliao/'.md5($this->user['userid']).'.jpg';
            if (!file_exists($document_path.$path)) {
                $access = $this->getaccess();
                $api = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access['access_token'];
                $can = [];
                $can['page']='pages/index/index';
                $can['scene']="parentid=".$this->user['userid'];
                $can['check_path']=false;
                $can['auto_color']=false;
                $can['width']=430;
                //$can['env_version']='develop';
                $res = Http::post($api, json_encode($can));

                if (!is_dir($document_path.'/uploads/yiliao')) {
                    mkdir(iconv("UTF-8", "GBK", $document_path.'/uploads/yiliao'), 0777, true);
                }
                $file = fopen($document_path.$path, "w");//创建件准备写入
                fwrite($file, $res);//写入
                fclose($file);//关闭
            }
            $row['ewm']=$this->apiurl.$path;
        } else {
            $row['ewm']=$this->apiurl."?parentid=".($this->user?$this->user['userid']:0);
        }
        //收藏
		if($this->user && $this->user['id']>0){
			$bookmark = Bookmark::where(['yiliao_user_id'=>$this->user['id'],'yiliao_pro_id'=>$row['id']])->find();
			if($bookmark){
				$row['shouc']=1;
			}else{
				$row['shouc']=0;
			}
		} else {
			$row['shouc']=0;
		}
        $row['catename'] = Procate::where(['status'=>'normal','id'=>$row['yiliao_procate_id']])->value('name');
            
        $this->success('success', $row);
    }
    //活动详情  单独处理
    public function promotiondetail()
    {
        $id = $this->request->param('id', 0);
        $hdid = $this->request->param('hdid', 0); //活动id
        $isminapp = $this->request->param('isminapp');
        $isshop = $this->request->param('isshop');
        $shopid = $this->request->param('shopid');

        if ($hdid>0) {
            $row = Promotion::where(['id'=>$hdid])->find();
//            $row = Pro::with(['cate'])->where('pro.id', $huodong['yiliao_pro_id'])->find();
//            $images = explode(',', $huodong['image']);
//            foreach ($images as $k => $v) {
//                $images[$k]=cdnurl($v, true);
//            }
            $row['image'] = cdnurl($row['image'], true);

//            if ($isshop==1) {
//                $shop = Shop::where(['id'=>$shopid])->find();
//                $shop['image'] = cdnurl($shop['image'], true);
//                $shopimages = explode(",", $shop['images']);
//                foreach ($shopimages as $k => $v) {
//                    $shopimages[$k] = cdnurl($v, true);
//                }
//                $shop['images'] = $shopimages;
//                $row['shop']=$shop;
//            } else {
//                //容错 单门店后台只选一个
//                $shops = Shop::where(['id'=>['in',$row['yiliao_shop_ids']],'status'=>'normal'])->order("weigh desc")->select();
//                $shop = $shops[0];
//                $shop['image'] = cdnurl($shop['image'], true);
//                $shopimages = explode(",", $shop['images']);
//                foreach ($shopimages as $k => $v) {
//                    $shopimages[$k] = cdnurl($v, true);
//                }
//                $shop['images'] = $shopimages;
//                $row['shop']=$shop;
//            }


//
//            $row['hdprice']=$huodong['price'];
//            $row['hd_end']=$huodong['end'];
//            $row['hdid']=$huodong['id'];
//            $row['content']=$huodong['content'];

        }
//        //海报
//        if($this->user && $this->user['userid']>0){
//            $data = UserModel::where(['id'=>$this->user['userid']])->find();
//            $row['userid'] =$this->user['userid'];
//            $row['nickname']=$data['nickname'];
//        }else {
//            $row['userid'] =0;
//            $row['nickname']='';
//        }
//        if ($isminapp==1 && $this->user && $this->user['userid']>0) {
//            //生成二维码
//            ///www/wwwroot/xx/public
//            $document_path = request()->server('DOCUMENT_ROOT');
//            $path = '/uploads/yiliao/'.md5($this->user['userid']).'.jpg';
//            if (!file_exists($document_path.$path)) {
//                $access = $this->getaccess();
//                $api = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access['access_token'];
//                $can = [];
//                $can['page']='pages/index/index';
//                $can['scene']="parentid=".$this->user['userid'];
//                $can['check_path']=false;
//                $can['auto_color']=false;
//                $can['width']=430;
//                //$can['env_version']='develop';
//                $res = Http::post($api, json_encode($can));
//
//                if (!is_dir($document_path.'/uploads/yiliao')) {
//                    mkdir(iconv("UTF-8", "GBK", $document_path.'/uploads/yiliao'), 0777, true);
//                }
//                $file = fopen($document_path.$path, "w");//创建件准备写入
//                fwrite($file, $res);//写入
//                fclose($file);//关闭
//            }
//            $row['ewm']=$this->apiurl.$path;
//        } else {
//            $row['ewm']=$this->apiurl."?parentid=".($this->user?$this->user['userid']:0);
//        }
//        //收藏
//        if($this->user && $this->user['id']>0){
//            $bookmark = Bookmark::where(['yiliao_user_id'=>$this->user['id'],'yiliao_pro_id'=>$row['id']])->find();
//            if($bookmark){
//                $row['shouc']=1;
//            }else{
//                $row['shouc']=0;
//            }
//        } else {
//            $row['shouc']=0;
//        }
//        $row['catename'] = Procate::where(['status'=>'normal','id'=>$row['yiliao_procate_id']])->value('name');

        $this->success('success', $row);
    }

    //随机热门项目
    public function remen()
    {
        $isshop = $this->request->param('isshop');
        $shopid = $this->request->param('shopid');
        $rand = rand();
        $where =[];
        $where['status']='normal';
        if ($isshop==1) {
            $where[] = ['exp',Db::raw("FIND_IN_SET('$shopid',yiliao_shop_ids)")];
        }
        $rows = Pro::where(['status'=>'normal'])->field("id,name,image,price,oldprice")->limit(4)->select();
        foreach ($rows as $k => $v) {
            $rows[$k]['image'] = cdnurl($v['image'], true);
        }
        $this->success('', $rows);
    }

    public function getpros()
    {
        $keyword = $this->request->param('keyword');
        $cateid = $this->request->param('cateid');
        $isshop = $this->request->param('isshop');
        $shopid = $this->request->param('shopid');
        $where=[];
        $where['A.status']='normal';
//        if ($isshop==1) {
//            $where[] = ['exp',Db::raw("FIND_IN_SET('$shopid',yiliao_shop_ids)")];
//        }
        if ($keyword) {
            $where['A.name']=['like',"%$keyword%"];
        } else {
            if ($cateid>0) {
                $where['A.yiliao_procate_id']=$cateid;
            }
        }
        $rows = Pro::where($where)->alias("A")->join("yiliao_procate C", "A.yiliao_procate_id=C.id")->order("A.paixu desc,A.id desc")->field("A.id,A.name,A.image,A.price,C.name as cate,A.desc,A.createtime")->select();
        foreach ($rows as $k => $v) {
            $rows[$k]['image'] = cdnurl($v['image'], true);
        }
        $this->success('', $rows);
    }
}
